# -*- coding: utf-8 -*-
# File : produce_service.py
# Author: taoyahui
# Date : 2021/10/17
from results import *
from utils import common_utils, id_utils
from services import user_service
from config import contract_name, contract_address, contract_abi
from models.food import Food
from models.produce_order import ProduceOrder
from models.create_producer import CreateProducer
import json


def create_production_order(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res,ensure_ascii=False)
    user = get_user_res['data']

    # 函数参数
    order_no = json_dict['order_no']
    order_type = json_dict['order_type']
    food_id = json_dict['food_id']
    price = json_dict['price']
    num = json_dict['num']
    sub_no = next(id_utils.unique_sequence)
    res = common_utils.common_bc_req(user.address, 'FoodTraceNew', 'Produces', [order_no, sub_no, order_type, food_id, price, num], contract_address,
                                     contract_abi)
    if res.status_code == 200:
        res_json = json.loads(res.text)
        if res_json['status'] == '0x0':
            return success_result
        else:
            return gen_result(500, res_json['message'])
    else:
        return gen_result(res.status_code, res.text)


def get_production_order(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res, ensure_ascii=False)
    user = get_user_res['data']
    id = json_dict['id']
    res = common_utils.common_bc_req(user.address, contract_name, 'getProduce', [id],
                                     contract_address,
                                     contract_abi)
    if res.status_code == 200:
        order_arr = json.loads(res.text)
        order = ProduceOrder(order_arr[0], order_arr[1], order_arr[2], order_arr[3],
                             order_arr[4], order_arr[5], common_utils.get_time(order_arr[6]), order_arr[7])
        return gen_result('200', order.__dict__)
    else:
        return gen_result(res.status_code, res.text)


def query_order(json_dict):
    page = json_dict['input_page']
    if 'order_no' in json_dict:
        trans_list = CreateProducer.query.filter_by(order_no=json_dict['order_no']).order_by(CreateProducer.pk_id.desc()).paginate(page, per_page=10, error_out=False).items
    else:
        trans_list = CreateProducer.query.order_by(CreateProducer.pk_id.desc()).paginate(page, per_page=10, error_out=False).items
    trans_list = [item.to_json() for item in trans_list]
    total = CreateProducer.query.count()
    return gen_result('200', {
        'total': total,
        'list':trans_list
    })